package com.system.cipher;

public class HEX {
	private static final byte hexTable[] = { 48, 49, 50, 51, 52, 53, 54, 55,
			56, 57, 97, 98, 99, 100, 101, 102 };

	public static byte[] encode(byte array[]) {
		return encode(array, 0, array.length);
	}

	public static byte[] encode(byte input[], int off, int length) {
		byte enc[] = new byte[length * 2];
		encode(input, off, length, enc, 0);
		return enc;
	}

	public static byte[] decode(String string) {
		byte bytes[] = new byte[string.length() / 2];
		String buf = string.toLowerCase();
		for (int i = 0; i < buf.length(); i += 2) {
			char left = buf.charAt(i);
			char right = buf.charAt(i + 1);
			int index = i / 2;
			if (left < 'a') {
				bytes[index] = (byte) (left - 48 << 4);
			} else {
				bytes[index] = (byte) ((left - 97) + 10 << 4);
			}
			if (right < 'a') {
				bytes[index] += (byte) (right - 48);
			} else {
				bytes[index] += (byte) ((right - 97) + 10);
			}
		}
		return bytes;
	}

	public static byte[] decode(byte array[]) {
		byte bytes[] = new byte[array.length / 2];
		decode(array, 0, array.length, bytes, 0);
		return bytes;
	}

	public static int getEncodedBlockSize() {
		return 2;
	}

	public static int encode(byte in[], int inOff, int length, byte out[],
			int outOff) {
		int i = 0;
		for (int j = 0; i < length; j += 2) {
			out[outOff + j] = hexTable[in[inOff] >> 4 & 0xf];
			out[outOff + j + 1] = hexTable[in[inOff] & 0xf];
			inOff++;
			i++;
		}
		return length * 2;
	}

	public static int getDecodedBlockSize() {
		return 1;
	}

	public static int decode(byte in[], int inOff, int length, byte out[],
			int outOff) {
		int halfLength = length / 2;
		for (int i = 0; i < halfLength; i++) {
			byte left = in[inOff + i * 2];
			byte right = in[inOff + i * 2 + 1];
			if (left < 97) {
				out[outOff] = (byte) (left - 48 << 4);
			} else {
				out[outOff] = (byte) ((left - 97) + 10 << 4);
			}
			if (right < 97) {
				out[outOff] += (byte) (right - 48);
			} else {
				out[outOff] += (byte) ((right - 97) + 10);
			}
			outOff++;
		}
		return halfLength;
	}
}